package com.example.loginregister.Manager

import android.content.Context
import com.example.loginregister.Model.PasswordType
import com.example.loginregister.Model.User
import java.lang.ref.WeakReference

class UserManager private constructor(private val context: WeakReference<Context>) {

    private val users = arrayListOf<User>()
    private val fileManager = FileManager.sharedInstance()

    //构造单例化对象
    companion object {
        private var instance: UserManager? = null
        fun sharedInstance(context: Context): UserManager {
            if (instance == null) {
                synchronized(this) {
                    if (instance == null) {
                        instance = UserManager(WeakReference(context))
                    }
                }
            }
            return instance!!
        }
    }

    //加载用户信息
    fun loadUserInfo() {
        fileManager.readData(context.get()!!).forEach {
            users.add(it)
        }
    }

    //判断是否有用户注册登录过
    fun hasUser() = users.size > 0

    //用户注册
    fun register(name: String, pin: String, pattern: String) {
        users.add(User(name, pin, pattern, false))
        fileManager.writeData(context.get()!!, users)
    }

    //用户登录
    fun login(name: String, password: String, type: PasswordType): Boolean {
        var user: User? = null
        users.forEach {
            if (name == it.name) {
                if (type == PasswordType.PIN) {
                    if(password == it.pin) {
                        user = it
                    }
                }
                if (type == PasswordType.PATTERN) {
                    if(password == it.pattern) {
                        user = it
                    }
                }
            }
        }
        return if (user != null) {
            currentUser().isLogin = false
            user!!.isLogin = true
            fileManager.writeData(context.get()!!, users)
            true
        } else false

    }

    //记录当前登录用户
    private fun currentUser(): User {
        users.filter { it.isLogin }.also {
            return it[0]
        }
    }

    fun exitLogin(){
        currentUser().isLogin = false
    }
}